package DAO;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Dictionary;

import android.content.ContentValues;
import android.content.Context;
import DAO.DBHelper;

import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;

import org.ksoap2.serialization.*;
import org.ksoap2.transport.HttpTransportSE;
import org.ksoap2.SoapEnvelope;



public class DBServices {
	
	public DBServices()
	{
		
	}
	
	private static final String NAMESPACE = "http://WebXml.com.cn/";
	 // WebService地址
    private static String URL = "http://www.webxml.com.cn/webservices/weatherwebservice.asmx";

    private static final String METHOD_NAME = "getWeatherbyCityName";

    private static String SOAP_ACTION = "http://WebXml.com.cn/getWeatherbyCityName";

    private String weatherToday;

    private SoapObject detail;
    
    public void getWeather(String cityName,Context context) {
        try {
                System.out.println("rpc------");
                SoapObject rpc = new SoapObject(NAMESPACE, METHOD_NAME);
                System.out.println("rpc" + rpc);
                System.out.println("cityName is " + cityName);
                rpc.addProperty("theCityName", cityName);

                
                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                envelope.bodyOut = rpc;
                envelope.dotNet = true;
                envelope.setOutputSoapObject(rpc);
                
                HttpTransportSE ht = new HttpTransportSE(URL);

                //AndroidHttpTransport ht = new AndroidHttpTransport(URL);
                ht.debug = true;

                ht.call(SOAP_ACTION, envelope);

                detail =(SoapObject) envelope.getResponse();
                
                //System.out.println("result" + result);
                System.out.println("detail" + detail);
                Toast.makeText(context, detail.toString(), Toast.LENGTH_LONG).show();
                parseWeather(detail, context);

                return;
        } catch (Exception e) {
                e.printStackTrace();
        }
}

private void parseWeather(SoapObject detail, Context context)
                throws UnsupportedEncodingException {
        String date = detail.getProperty(6).toString();
        weatherToday = "今天：" + date.split(" ")[0];
        weatherToday = weatherToday + "\n天气：" + date.split(" ")[1];
        weatherToday = weatherToday + "\n气温："
                        + detail.getProperty(5).toString();
        weatherToday = weatherToday + "\n风力："
                        + detail.getProperty(7).toString() + "\n";
        System.out.println("weatherToday is " + weatherToday);
        Toast.makeText(context, weatherToday, Toast.LENGTH_LONG).show();

}



    
	
	
	//返回所有查询结果，每一行结果以哈希表的结构存储于ArrayList中
	public  ArrayList<Dictionary> ExecuteReader1(String cmdtext, Context context)
	{
		ArrayList<Dictionary> al = new ArrayList<Dictionary>();
		DBHelper dh = new DBHelper(context, "yundongling.db", null, 1);
		try
		{
		 Cursor cur = dh.query(cmdtext, null);
		 //在执行了getWritableDatabase()以后，数据库才算真正建立，对数据库中表的操作才能起效。
		 while (cur.moveToNext())
		 { 
			 Dictionary temp = new java.util.Hashtable();
			 for (int i = 0; i < cur.getColumnCount(); i++)
			 {
				 if (cur.getString(i) == null)
				 {
					 temp.put(cur.getColumnName(i).toString(), "");
				 }
				 else
				 {
					 temp.put(cur.getColumnName(i).toString(), cur.getString(i));
				 }
			 }
			 al.add(temp);
		 }
		}
		catch (SQLException ex)
		{
			ex.printStackTrace();
			throw new SQLException("executeSql:" + ex.toString());
		}
		finally
		{
			dh.close();
		}
		return al;
	}
	
	/*	String tName = "XFIT_Day_Summary";   //表名
	ContentValues cValue = new ContentValues();
	cValue.put("DaySummaryID", String.valueOf(i));
	cValue.put("SummaryDate", "'2011-11-08 00:00:00.000'");
	cValue.put("UserID", "91");
	cValue.put("SportTime", "3060.00");
	cValue.put("Calorie", "0.2269900000");
	cValue.put("Distance", "112.4151949025"); //插入的行信息*/
	
	//插入单行数据
	public  long ExecuteInsertSingle(ContentValues cVals, Context context, String tName)
	{
		DBHelper dh = new DBHelper(context, "yundongling.db", null, 1);
		
		long result = 0;
		
		try
		{
			 long tempRe = dh.executeInsert(cVals, tName);
			 result = tempRe;
		}
		catch (SQLException ex)
		{
			ex.printStackTrace();
			throw new SQLException("executeSql:" + ex.toString());
		}
		return result;
	}
	
	public void buildDB(Context context)
	{
		DBHelper dh = new DBHelper(context, "yundongling.db", null, 1);
		SQLiteDatabase db = dh.getWritableDatabase();
	}
	
	public long ExecuteDeleteSingle(int ID, Context context, String tName)
	{
		DBHelper dh = new DBHelper(context, "yundongling.db", null, 1);
		long result = 0;
		SQLiteDatabase db = dh.getWritableDatabase();
		String where = "ID=" + String.valueOf(ID);
		result = db.delete(tName, where, null);
		return result;
	}
	
	public long ExecuteInsertMultiple(ArrayList<ContentValues> vals, Context context, String tName)
	{
		DBHelper dh = new DBHelper(context, "yundongling.db", null, 1);
		SQLiteDatabase sq = dh.getWritableDatabase();
		long result = 0;
		try
		{
			sq.beginTransaction();
			for (int i = 0; i < vals.size(); i++)
			{
				long temp = sq.insert(tName, null, vals.get(i));
				if (temp != -1)
				{
					result++;
				}
			}
			sq.setTransactionSuccessful();
		}
		catch (SQLException ex)
		{
			ex.printStackTrace();
			throw new SQLException("executeSql:" + ex.toString());
		}
		finally
		{
			sq.endTransaction();
			sq.close();
		}
		return result;
	}
	
	//批量导入数据
	public void insertMountData(Context context)
	{
		DBHelper dh = new DBHelper(context, "yundongling.db", null, 1);
		SQLiteDatabase sq = dh.getWritableDatabase();
		dh.insertTest(sq);
	}
	
	
	
	public boolean Login(String userName, String passWord, Context context)
	{
		boolean result = false;
		String sql = "SELECT id FROM AllUsers WHERE name='" + userName + "' + AND key='" + passWord + "'";
		 ArrayList<Dictionary> all = ExecuteReader1(sql, context);
		 if (all.get(0).get(0) == "")
		 {
			 result = true;
		 }
		return result;
	}
	
	public Cursor get20running(String sql, Context context)
	{
		DBHelper dh = new DBHelper(context, "yundongling.db", null, 1);
		Cursor result = dh.query(sql, null);
		return result;
	}
	
	public void executeDelete(String sql, Context context)
	{
		DBHelper dh = new DBHelper(context, "yundongling.db", null, 1);
		SQLiteDatabase sq = dh.getWritableDatabase();
		sq.execSQL(sql);
	}
	
	public void executeUpdate(String sql, Context context)
	{
		DBHelper dh = new DBHelper(context, "yundongling.db", null, 1);
		SQLiteDatabase sq = dh.getWritableDatabase();
		sq.execSQL(sql);
	}
}
